// components/search/index.js
import {
  KeywordModel
} from '../../models/keyword.js'
import {
  BookModel
} from '../../models/book.js'

import {
  paginationBev
} from '../behaviors/pagination.js'
const keywordModel = new KeywordModel()
const bookModel = new BookModel()
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hostWords: [],
    searching: false,
    q: '',
    loading: false,
    loadingCenter:false
  },

  attached() {
    keywordModel.getHot().then(res => {
      this.setData({
        hostWords: res.hot
      })
    })
    this.setData({
      historyWords: keywordModel.getHistory(),
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore() {
      if (!this.data.q) {
        return
      }
      if (this.isLocked()) {
        return
      }
      const length = this.data.dataArray.length;
      if (this.hasMore()) {
        this.locked()
        bookModel.search(this.getCurrentStart(), this.data.q).then(res => {
          this.setMoreData(res.books)
          this.unLocked();
        },()=>{
          this.unLocked();
        })
      }
    },
    
   

    onCancel: function(e) {
      this.triggerEvent('cancel', {}, {})
      this.initialize();
    },
    onConfirm(e) {
      const q = e.detail.value || e.detail.text;
      if(q==null||''){
        return
      }      
      this._showResult();
      this._showLoadingCenter()
      // this.initialize();
      bookModel.search(0, q)
        .then(res => {
          this.setMoreData(res.books)
          this.setTotal(res.total)
          this.setData({
            q
          })
          keywordModel.addToHistory(q);
          this._hideLoadingCenter()
        })
    },
    onDelete(e) {
      this._closeRsult()
      this.initialize();
    },

    _showLoadingCenter(){
      this.setData({
       loadingCenter:true
      })
    },  

    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    },  

    _showResult() {
      this.setData({
        searching: true
      })
    },

    _closeRsult(){
      this.setData({
        searching: false,
        q:''
      })
    }
  }
})